package com.example.backend.controller;

import com.example.backend.entity.Warehouse;
import com.example.backend.service.WarehouseService;
import com.example.backend.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;

@RestController
@RequestMapping("/api/warehouse")
public class WarehouseController {
    @Autowired
    private WarehouseService warehouseService;

    @PreAuthorize("hasAuthority('ADMIN')")
    @PostMapping
    public ApiResponse<String> addWarehouse(@RequestBody Warehouse warehouse) {
        warehouseService.addWarehouse(warehouse);
        return ApiResponse.success("添加成功");
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @GetMapping("/{id}")
    public ApiResponse<Warehouse> getWarehouseById(@PathVariable("id") Long id) {
        Warehouse warehouse = warehouseService.getWarehouseById(id);
        if (warehouse != null) {
            return ApiResponse.success(warehouse);
        }
        return ApiResponse.error(404, "仓库不存在");
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @GetMapping
    public ApiResponse<List<Warehouse>> getAllWarehouses() {
        return ApiResponse.success(warehouseService.getAllWarehouses());
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @PutMapping
    public ApiResponse<String> updateWarehouse(@RequestBody Warehouse warehouse) {
        warehouseService.updateWarehouse(warehouse);
        return ApiResponse.success("更新成功");
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteWarehouse(@PathVariable("id") Long id) {
        int result = warehouseService.deleteWarehouse(id);
        if (result > 0) {
            return ApiResponse.success("删除成功");
        } else {
            return ApiResponse.error(404, "删除失败，仓库不存在或无法删除");
        }
    }
} 